package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.config.RedisConfiguration;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.DishExistException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @projectName: sky-take-out
 * @package: com.sky.service.impl
 * @className: DishServiceImpl
 * @author: Eric
 * @description: TODO
 * @date: 2023/9/22 10:16
 * @version: 1.0
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DishServiceImpl implements DishService {
    private final DishMapper dishMapper;

    private final DishFlavorMapper dishFlavorMapper;

    private final SetmealDishMapper setmealDishMapper;

    private final RedisTemplate redisTemplate;

    @Override
    @Transactional
    public void creat(DishDTO dishDTO) {
        // 判断是否有重名
        Integer count = dishMapper.getCountDishName(dishDTO.getName());
        if (count>0){
            throw new DishExistException(MessageConstant.ERROR_DISH_NAME);
        }
        // 1.添加菜品
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setStatus(StatusConstant.DISABLE);
        dishMapper.insert(dish);
        // 2.批量添加口味
        creatFlavors(dishDTO, dish);

        // 清空缓存
        redisTemplate.delete(getCacheKey(dishDTO.getCategoryId()));
    }

    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Dish dishQuery = new Dish();
        BeanUtils.copyProperties(dishPageQueryDTO,dishQuery);
        List<Dish> dishes = dishMapper.selectList(dishQuery);
        PageInfo<Dish> pageInfo = new PageInfo<>(dishes);
        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
    }

    @Override
    @Transactional
    public void deleteBatchByIds(List<Long> ids) {
        // 1.起售的不能删除
        Integer countByIdsAndStatus = dishMapper.selectCountByIdsAndStatus(ids,StatusConstant.ENABLE);
        if (countByIdsAndStatus>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        // 2.有关联的不能删除
        Integer countByDishIds= setmealDishMapper.selectCountByDishIds(ids);
        if (countByDishIds>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 批量删除
        dishMapper.deleteBatchByIds(ids);
        // 删除口味
        dishFlavorMapper.deleteByDishIds(ids);
    }

    @Override
    public DishVO queryDish(Long id) {
        Dish dish = dishMapper.getDishById(id);
        List<DishFlavor> dishFlavors = dishFlavorMapper.getDishFlavorById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    @Override
    @Transactional
    public void updateDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.updateDish(dish);
        dishFlavorMapper.deleteByDishIds(Collections.singletonList(dishDTO.getId()));
        creatFlavors(dishDTO,dish);
        redisTemplate.delete(getCacheKey(dishDTO.getCategoryId()));
    }

    @Override
    public void changeStatus(Long id,Integer status) {
        dishMapper.changeStatus(id,status);
    }

    @Override
    public List<Dish> queryDishByCategoryId(Long categoryId) {
        List<Dish> dish = dishMapper.queryDishByCategoryId(categoryId);
        return dish;
    }

    @Override
    public List<Dish> dishList(Long categoryId) {
        // 在这加一个缓存的查询
        // 第一次redis中没有数据? -> 初始化数据  查空则走数据库

        // 1.解决redis中的数据存与取的问题  -->  String
        long startCache = System.currentTimeMillis();
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String cacheKey = getCacheKey(categoryId);
        String vos = (String)valueOperations.get(cacheKey);
        if (StringUtils.hasText(vos)){
            List<Dish> dishList = JSON.parseArray(vos, Dish.class);
            long endCache = System.currentTimeMillis();
            log.info("走缓存消耗的时间:" + (endCache-startCache));
            return dishList;
        }
        Dish dishNew = new Dish();
        dishNew.setCategoryId(categoryId);
        List<Dish> dishList = dishMapper.selectList(dishNew);
        for (Dish dish : dishList) {
            dish.setFlavors(dishMapper.selectDishFlavor(dish.getId()));
        }
        long endMySQL = System.currentTimeMillis();
        log.info("走数据库消耗的时间:"+(endMySQL-startCache));
        // 放进redis中 -> json
        valueOperations.set(cacheKey,JSON.toJSONString(dishList));
        return dishList;
    }

    private void creatFlavors(DishDTO dishDTO, Dish dish) {
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (CollectionUtils.isNotEmpty(flavors)) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dish.getId());
            }
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    private String getCacheKey(Long categoryId) {
        String cacheKey = "DISH_BY_CATEGORY_ID:" + categoryId;
        return cacheKey;
    }
}
